package com.yunc.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunc.base.utils.R;
import com.yunc.modules.sys.entity.SysRole;
import com.yunc.modules.sys.entity.SysRoleMenu;
import com.yunc.modules.sys.entity.SysUserRole;
import com.yunc.modules.sys.mapper.SysRoleMapper;
import com.yunc.modules.sys.service.ISysRoleMenuService;
import com.yunc.modules.sys.service.ISysRoleService;
import com.yunc.modules.sys.service.ISysUserRoleService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * 系统角色
 *
 * @author congcong tao
 * @date 2018/5/14 16:17
 */
@Service("sysRoleService")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper,SysRole> implements ISysRoleService {

    private final ISysUserRoleService sysUserRoleService;
    private final ISysRoleMenuService sysRoleMenuService;
    private final SysRoleMapper sysRoleMapper;

    @Override
    public R deleteRole(String roleId) {
        // 查询是否有用户存在该角色
        QueryWrapper<SysUserRole> ew = new QueryWrapper<>();
        ew.eq("role_id", roleId);
        int count = sysUserRoleService.count(ew);
        if (count > 0) {
            return R.error("存在用户拥有该权限，不可删除");
        }
        boolean flag = this.removeById(roleId);
        if (flag) {
            return R.ok();
        }
        return R.error();
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public R saveRole(SysRole role) {
        role.setCreateTime(new Date());
        boolean flag = this.save(role);
        if (flag) {
            // 修改权限
            boolean roleMenuFlag = sysRoleMenuService.insertList(role.getId(), role.getMenuIds());
            if (roleMenuFlag) {
                return R.ok();
            }
        }
        return R.error();
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public R updateRole(SysRole role) {
        String roleId = role.getId();
        boolean flag = this.updateById(role);
        if (flag) {
            // 删除权限
            SysRoleMenu record = new SysRoleMenu();
            record.setRoleId(roleId);
            sysRoleMenuService.remove(new QueryWrapper<>(record));
            boolean roleMenuFlag = sysRoleMenuService.insertList(role.getId(), role.getMenuIds());
            if (roleMenuFlag) {
                return R.ok();
            }
        }
        return R.error();
    }

    @Override
    public int getDataScopeAll(String userId) {
        return sysRoleMapper.getDataScopeAll(userId);
    }
}
